#include "towers.h"

static char     check_tow_pos(s_tow_list *l, int pos[2])
{
    while (l && !(pos[0] == l->pos[0] && pos[1] == l->pos[1]))
        l = l->next;

    return (!l);
}

/**
** @brief Add an element to the towers list in the object structrure
**
** @param Type of the element
** @param Object containing the towers list
** @param Array containing the position of the element
*/
void            add_to_tow_list(e_tow type, s_object *object, int pos[2])
{
    s_tow_list  *l = object->tow_list;

    if (!check_tow_pos(l, pos))
    {
        fprintf (stderr, "[!] Already a tower here ! (y:%d, x:%d)\n",
                 pos[0], pos[1]);
        return;
    }

    if (object->gold < 20)
    {
        fprintf(stderr, "[!] Not enough money to buy tower ! ($:%d)\n",
                object->gold);
        return;
    }

    object->gold -= 20;
    s_tow_list *n;

    n = malloc(sizeof (s_tow_list));

    n->id = (l) ? (l->id + 1) : 0;
    n->pos[0] = pos[0];
    n->pos[1] = pos[1];
    n->type = type;
    n->next = l;

    fprintf(stderr, "[+] Tower (id: %d)\n", n->id);

    object->tow_list = n;
}

/**
** @brief Delete an element of the towers list in the object structrure
**
** @param ID of the element
** @param Object containing the towers list
*/
void            del_from_tow_list(int id, s_object *object)
{
    s_tow_list  *old = NULL;
    s_tow_list  *curr = object->tow_list;

    while (curr && curr->next && curr->id != id)
    {
        old = curr;
        curr = curr->next;
    }

    if (curr == NULL)
    {
        printf("Liste nulle\n");
        return;
    }

    if (curr->id != id)
    {
        printf("Element non trouvé\n");
        return;
    }

    if (old == NULL)
        object->tow_list = curr->next;
    else
        old->next = curr->next;

    free(curr);
}

/**
** @brief Display the element of the towers list in the object structrure
**
** @param Object containing the towers list
*/
void            print_tow_list(s_object *object)
{
    SDL_Rect    pos;
    s_tow_list  *l = NULL;
    int         i = 1;

    l = object->tow_list;
    while (l)
    {
        pos.x = l->pos[1] * IMG_X;
        pos.y = l->pos[0] * IMG_Y;

        SDL_BlitSurface(object->tow[l->type], NULL, object->screen, &pos);
        l = l->next;
        i++;
    }
}
